/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
import tresenraya.*;
import static utilidades.constantes.*;

/**
 *
 * @author Helena
 */
public class MouseHandler extends MouseAdapter{

    private Posicion posicion;
    Tablero tablero;
    int iOrigen = 0;
    int jOrigen = 0;
    int iDestino = 0;
    int jDestino = 0;

    public MouseHandler(Posicion posicion, Tablero tablero)
    {
        this.posicion = posicion;
        this.tablero = tablero;
    }

    @Override
    public void mouseEntered(MouseEvent e)
    {
        String name = ((JPanel) e.getSource()).getName();

        System.out.println("wellcome to square " + name);

        iDestino = Integer.parseInt(name.substring(5, 6));
        jDestino = Integer.parseInt(name.substring(6, 7));
        System.out.println("I origen: " + iOrigen + "; j origen: " + jOrigen);
   }

    @Override
    public void mousePressed(MouseEvent e)
    {
        String name = ((JPanel) e.getSource()).getName();

        System.out.println("Mouse pressed in " + name);

        System.out.println(name.substring(5, 6));
        System.out.println(name.substring(6, 7));

        if (posicion.getTurno()==JUGADOR_1)
        {
            int i = Integer.parseInt(name.substring(5, 6));
            int j = Integer.parseInt(name.substring(6, 7));

            if (posicion.preCondicionPonerFicha(i, j))
            {
                posicion.ponerFicha(i, j);
                tablero.pintarFicha(JUGADOR_1, i, j);
            }
            iOrigen = i;
            jOrigen = j;
        }
    }

    @Override
    public void mouseReleased(MouseEvent e)
    {
        String name = ((JPanel) e.getSource()).getName();

        System.out.println("Mouse released in " + name);

        if (posicion.getTurno() == JUGADOR_1)
        {
            if (posicion.preCondicionMoverFicha(iOrigen, jOrigen, iDestino, jDestino))
            {
                posicion.moverFicha(iOrigen, jOrigen, iDestino, jDestino);
                tablero.borrarFicha(iOrigen, jOrigen);
                tablero.pintarFicha(JUGADOR_1, iDestino, jDestino);
            }
        }
    }

    /**
     * @param posicion the posicion to set
     */
    public void setPosicion(Posicion posicion) {
        this.posicion = posicion;
    }
}
